package steed.util.system;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import org.redisson.api.RMapCache;

import steed.hibernatemaster.domain.BaseRelationalDatabaseDomain;
import steed.util.redis.RedissonUtil;
import steed.util.system.DataCacheUtil.DataCacheEngine;

/**
 * redis数据库缓存引擎,不提倡直接用该类,建议通过DataCacheUtil来使用
 * @author 战马
 * 
 * @see DataCacheUtil
 */
public class RedisDataCacheEngine implements DataCacheEngine{
	
	public <T> T getData(String key,String prefix){
		return (T) getMapCache().get(getKey(key, prefix));
	}
	
	public void setData(String key,String prefix,Serializable value){
		setData(key, prefix, value, 1000*60*60*2L);
	}
	
	public void setData(String key,String prefix,Serializable value,Long lifeTime){
		RMapCache<Object, Object> mapCache = getMapCache();
		String key2 = getKey(key, prefix);
		if (value instanceof BaseRelationalDatabaseDomain) {
			value = ((BaseRelationalDatabaseDomain)value).hibernateProxCollection2javaCollection();
		}
		if (lifeTime == null) {
			mapCache.fastPut(key2, value);
		}else {
			mapCache.fastPut(key2, value, lifeTime, TimeUnit.MILLISECONDS);
		}
	}

	private String getKey(String key, String prefix) {
		String key2 = key+"_steed_dataCache_"+prefix;
		return key2;
	}

	private RMapCache<Object, Object> getMapCache() {
		RMapCache<Object, Object> mapCache = RedissonUtil.getRedisson().getMapCache("steed.util.system.RedisDataCacheEngineRedisMap");
		return mapCache;
	}
	

	@Override
	public void setPermanentData(String key, String prefix, Serializable value) {
		setData(key, prefix, value, null);
	}

	@Override
	public void removeData(String key, String prefix) {
		getMapCache().remove(getKey(key, prefix));
		
	}
	
}
